package com.sti.platform.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.activiti.engine.HistoryService;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.impl.RepositoryServiceImpl;
import org.activiti.engine.impl.pvm.ReadOnlyProcessDefinition;
import org.activiti.engine.impl.pvm.process.ActivityImpl;
import org.activiti.engine.task.Task;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.aisino.core.server.BaseService;
import com.sti.platform.model.ActUserLcsl;
import com.sti.platform.model.Busioness;
import com.sti.platform.model.TbOpinion;
import com.sti.platform.service.ActivitiService;
import com.sti.platform.service.BusinossService;
import com.sti.platform.util.ActUtil;
import com.sti.platform.util.JDJumpTaskCmd;

@Service
public class ActivitiServiceImpl extends BaseService implements ActivitiService {

	@Autowired
	private TaskService taskService;
	@Autowired
	private RuntimeService runtimeService;
	@Autowired
	private RepositoryServiceImpl repositoryService;
	@Autowired
	private HistoryService historyService;
	@Autowired
	private ProcessEngine processEngine;
	@Autowired
	private BusinossService businossService;
	
	@Override
	public List<Map<String,Object>> createProcessInstance(String title,String context){
		Map<String,Object> map = new HashMap<String, Object>();
		String applicant = "300003";//流程发起人
		map.put("applicant", applicant);
		map.put("title", title);
		map.put("context", context);
		String lcslId = ActUtil.createProcessInstance(map,repositoryService,runtimeService);//启动流程
		
		//保存申请模板内容
		Busioness busioness = new Busioness();
		busioness.setTitle(title);
		busioness.setContext(context);
		busioness.setCjr(applicant);
		super.save(busioness);
		ActUserLcsl actUser = new ActUserLcsl();
		actUser.setLcslId(lcslId);
		actUser.setYwId(busioness.getId());
		super.save(actUser);
		
		Map<String,Object> remap = new HashMap<String,Object>();
		remap.put("userId", applicant);
		List<Task> tasks = ActUtil.queryTask(applicant,lcslId,taskService);
		for(Task task :tasks){
			ActUtil.completeTask(task.getId(),map, taskService);
		}
		
		List<Map<String,Object>> list = businossService.queryStartUpBusiness(applicant);
		return  list;
	}
	
	@Override
	public List<Map<String,Object>> queryTask(String userId) {
		List<Map<String,Object>> reList = new ArrayList<Map<String,Object>>();
		List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
		List<String> allList = new ArrayList<String>();
		List<Task> tasks = ActUtil.queryTask(userId,taskService);
		for(Task task :tasks){
			Map<String,Object> map = new HashMap<String,Object>();
			String taskName = task.getName();
			String taskId = task.getId();
			String lcslId = task.getProcessInstanceId();
			map.put("taskName", taskName);
			map.put("taskId", taskId);
			map.put("lcslId", lcslId);
			result.add(map);
		}
		List<Map<String,Object>> hisList = queryhisTask(userId);
		result.addAll(hisList);
		for(Map<String,Object> li :result){
			String lcslId = MapUtils.getString(li, "lcslId");
			String currName = queryCurrentTask(lcslId);
			List<Map<String,Object>> opinionList = businossService.queryOpinion(lcslId);
			if(opinionList.size() > 0){
				li.put("opinion", opinionList);
			}
			li.put("userId", userId);
			if(!allList.contains(lcslId)){
				allList.add(lcslId);
				if(currName == null){
					currName ="审核已结束";
					li.put("state", "结束");
				} else {
					li.put("state", "审核中");
				}
				Busioness businoss = businossService.queryTobeAuditedTask(lcslId);
				
				li.put("title", businoss.getTitle());
				li.put("context", businoss.getContext());
				li.put("currName", currName);
				reList.add(li);
			}
		}
		return reList;	
	}
	
	@Override
	public String queryCurrentTask(String lcslId){
	    return ActUtil.queryCurrentTask(lcslId, taskService);
	}
	
	@Override
	public Long queryTaskCount(String userId) {
		return ActUtil.queryTaskCount(userId,taskService);	
	}
	
	@Override
	public List<Map<String,Object>> queryhisTask(String userId){
		return ActUtil.getHisActivitiList(userId,processEngine);
	}

	@Override
	public String completeTask(String taskId,String users,String opinion,String userId) {
		Map<String,Object> map = new HashMap<>();
		map.put("userId", userId);
		if(users!= null){
			String[] list = users.split(",");
			map.put("users", list);
		}
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String lcslId = task.getProcessInstanceId();
		//存储审核意见
		if(opinion!=null&&opinion!="" && userId != null && userId != ""){
			TbOpinion tbOpinion = new TbOpinion();
			tbOpinion.setLcslId(lcslId);
			tbOpinion.setOpinion(opinion);
			tbOpinion.setUserId(userId);
			super.save(tbOpinion);
		}
		try{
			ActUtil.completeTask(taskId,map, taskService);
		}catch(Exception e){
			return "请添加专家";
		}
		return "";
	}
	
	@Override
	public String saveCandidateUser(String processinstanceId,String users){
		List<String> list = new ArrayList<String>();
		Task task = taskService.createTaskQuery().processInstanceId(processinstanceId).singleResult();
		list.add("500005");
		for(String user : list){
			//taskService.addCandidateUser(task.getId(), user);
			taskService.setAssignee(task.getId(), user);
		}
		return "";
	}

	@Override
	public Map<String, Object> updateTaskRoll(String taskId,String destinationTaskId) {
		Map<String,Object> result = new HashMap<String,Object>();
		Task task = taskService.createTaskQuery().taskId(taskId).singleResult();
		String executionId = task.getExecutionId();
		String lcdyId = task.getProcessDefinitionId();
		String processTaskId = task.getId();
		List<Map<String,Object>> activities = ActUtil.getCandidateUserIdExpressions(lcdyId,repositoryService);
		Map<String,Object> remap = new HashMap<String, Object>();
		for(Map<String,Object> map :activities){
			if(destinationTaskId.equals(MapUtils.getString(map, "activityId"))){
				remap.put("candidate", MapUtils.getString(map, "candidates"));
				break;
			}
		}
		Map<String, Object> vars = new HashMap<String, Object>();  
		@SuppressWarnings("unchecked")
		List<String> candidates = (List<String>) vars.get("candidate");
		vars.put("candidateList", candidates);
		
		ReadOnlyProcessDefinition processDefinitionEntity = (ReadOnlyProcessDefinition) repositoryService.getProcessDefinition(lcdyId);  
		ActivityImpl destinationActivity = (ActivityImpl) processDefinitionEntity.findActivity(destinationTaskId);// 目标节点   
	    ActivityImpl currentActivity = (ActivityImpl)processDefinitionEntity.findActivity(processTaskId);// 当前节点   
	    processEngine.getManagementService().executeCommand(new JDJumpTaskCmd(executionId,destinationActivity,vars,currentActivity)); 
		result.put("success", true);
		result.put("info", "回退成功");
		return result;
	}
	

	@Override
	public List<Map<String, Object>> queryUser() {
		List<Map<String,Object>> list = new ArrayList<Map<String,Object>>();
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userName","李四");
		map.put("userId", "200002");
		list.add(map);
		Map<String,Object> map2 = new HashMap<String,Object>();
		map2.put("userName","王五");
		map2.put("userId", "400004");
		list.add(map2);
		return list;
	}
	
}
